package model;

import java.util.HashMap;

import view.Scanner;
import android.graphics.Point;
import android.graphics.Rect;

import com.google.zxing.Result;
import com.google.zxing.ResultPoint;

public class HolderFactory 
{	
	private Scanner _observer;
	
	public HolderFactory() {}
	
	/**
	 * Checks given list of holders for already present holders and creates or updates them accordingly
	 * @param holders The list to check.
	 * @param results The list currently visible QR-code data.
	 * @param observer The Activity responsible for observing the holders
	 * @param handler The handler for handling webservice connection
	 * @return A renewed list of holders.
	 */
	public HashMap<String, Holder> updateHolders(HashMap<String, Holder> holders, Result[] results, Scanner observer, ThreadHandler handler)
	{
		_observer = observer;
		
		for (Result result : results) 
		{
			String id = result.toString();
			
			//Update holder location if it already exists
			if(holders.containsKey(id))
				holders.get(id).setSurface(calculateRectangle(result.getResultPoints()));
			else //Create new holder
				holders.put(id, createHolder(result, handler));
		}
		
		return holders;
	}
	
	//Create a new Holder from QR-code Data
	private Holder createHolder(Result result, ThreadHandler handler)
	{
		Rect surface = calculateRectangle(result.getResultPoints());
		
		String id = result.toString();
		
		Holder holder = new Holder(id, surface, handler);
		addObserverToHolder(holder);
		
		return holder;
	}
	
	/**
	 * Calculate the location of the QR-code on screen from ResultPoint[]
	 * @param An array of 3 ResultPoints representing  the following corners of a QR-code accordingly: lower left, upper left, upper right.
	 * @return The rectangle of the location on screen
	 */
	private Rect calculateRectangle(ResultPoint[] points)
	{
		Point lowerLeft = new Point((int) points[0].getX(), (int) points[0].getY());
		
		Point upperLeft = new Point((int) points[1].getX(), (int) points[1].getY());
		
		Point upperRight = new Point((int) points[2].getX(), (int) points[2].getY());
		
		Rect rect = new Rect(upperLeft.x, upperLeft.y, upperRight.x, lowerLeft.y);
				
		return rect;
	}
	
	private void addObserverToHolder(Holder holder)
	{
		_observer.addNewHolderView(holder);
		holder.notifyObservers();
	}
}
